#include "OpenCVImg.h"


COpenCVImg::COpenCVImg(void):m_pImg(NULL),m_bColor(true)
{
}


COpenCVImg::~COpenCVImg(void)
{
	if(m_pImg)
		cvReleaseImage(&m_pImg);	
}

void COpenCVImg::CreateImg(CvSize imgSize, int iDepth, int iChannel)
{
	if(m_pImg)
		cvReleaseImage(&m_pImg);

	m_pImg = cvCreateImage(imgSize, iDepth, iChannel);
}

void COpenCVImg::loadImg(char* strFileName,bool bColor)
{
	if(m_pImg)
		cvReleaseImage(&m_pImg);

	if (bColor)
		m_pImg = cvLoadImage(strFileName,CV_LOAD_IMAGE_COLOR);
	else
		m_pImg = cvLoadImage(strFileName,CV_LOAD_IMAGE_GRAYSCALE);

	m_bColor = bColor;
}

int COpenCVImg::saveImg(char* strFileName)
{
	return cvSaveImage(strFileName,m_pImg);
}


void COpenCVImg::GetPixelFromColorImg(int xIdx, int yIdx, uchar& red, uchar& green, uchar& blue)
{
	if(!m_pImg) return;

	uchar* ptr = (uchar*) ( m_pImg->imageData + yIdx * m_pImg->widthStep );

	blue = ptr[3*xIdx];//blue
	green = ptr[3*xIdx+1];//green
	red = ptr[3*xIdx+2];//red		
}

void COpenCVImg::GetPixelFromGrayImg(int xIdx, int yIdx, uchar& gray)
{
	uchar* ptr = (uchar*) ( m_pImg->imageData + yIdx * m_pImg->widthStep );

	gray = ptr[xIdx];//blue		
}

void COpenCVImg::FillImageRegionWithSingleColor(Rect& r, uchar red, uchar green, uchar blue)
{
	//modify the pixel regions
	for( int y=r.y; y<(r.y+r.height); y++ ) { 
		uchar* ptr = (uchar*) ( m_pImg->imageData + y * m_pImg->widthStep ); 
		for( int x=r.x; x<(r.x+r.width); x++ ) { 
			ptr[3*x] = blue;ptr[3*x+1] = green;ptr[3*x+2] = red;
		} //Set red to max (BGR format)

	}
}

void COpenCVImg::FillImageRegionWithSingleGray(Rect& r, uchar gray)
{
	//modify the pixel regions
	for( int y=r.y; y<(r.y+r.height); y++ ) { 
		uchar* ptr = (uchar*) ( m_pImg->imageData + y * m_pImg->widthStep ); 
		for( int x=r.x; x<(r.x+r.width); x++ ) 
			ptr[x] = gray;
	}
}	

//copy the content from iplimage to mat
void COpenCVImg::CopyImageRegionToSingleChannelMat(IplImage* mat, Rect& r)
{
	//modify the pixel regions
	for( int y=r.y; y<(r.y+r.height); y++ ) { 
		uchar* ptr = (uchar*) ( m_pImg->imageData + y * m_pImg->widthStep );
		uchar* ptrROI = (uchar*) ( mat->imageData + (y-r.y) * mat->widthStep );
		for( int x=r.x; x<(r.x+r.width); x++ ) { 
			if(m_bColor)//3 channels
				ptrROI[(x-r.x)] = ptr[3*x];
			else
				ptrROI[(x-r.x)] = ptr[x];
		}
	}	
}

void COpenCVImg::CreateScaledImg(COpenCVImg* srcImg, float fScaleFactor)
{
	if(m_pImg!=NULL)
		cvReleaseImage(&m_pImg);

	m_pImg = cvCreateImage( cvSize((int)((srcImg->GetWidth()*fScaleFactor)) , (int)((srcImg->GetHeight()*fScaleFactor)) ),	
		srcImg->GetDepth(), srcImg->GetChannels() );

	cvResize(srcImg->GetImgPointer(),m_pImg);
}